package com.reader.api.controller.usercenter;

import com.reader.api.controller.BaseController;
import com.reader.api.entity.usercenter.APPToken;
import com.reader.api.entity.usercenter.DeviceInfo;
import com.reader.api.exception.register.RegisterException;
import com.reader.api.service.usercenter.IAPPTokenService;
import com.reader.api.service.usercenter.IUserService;
import com.reader.api.service.usercenter.RegisterService;
import com.reader.api.utils.IpUtils;
import com.reader.core.entity.ResultMessageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liujianqing
 * @date 2018/10/24
 */
@RestController
@RequestMapping("/api/reg/")
public class RegisterController extends BaseController<Object>{
    @Autowired
    private RegisterService registerService;
    @Autowired
    private IUserService iUserService;

    @GetMapping(value="sms")
    @ResponseBody
    public ResultMessageInfo sms(@RequestParam(value = "mobile") String mobile,
                                 HttpServletRequest request){
        if(StringUtils.isBlank(mobile)){
            return ResultMessageInfo.ofMessage("手机号非法");
        }

        String ip= IpUtils.findIpFromRequest(request);
        boolean checkRet = false;
        try {
            checkRet = registerService.checkMobileAndIpCanSendCode(mobile,ip);
        }catch (RegisterException e){
            return ResultMessageInfo.ofMessage(e.getMsg());
        }

        if(checkRet){
            registerService.sendRegisterMobileCode(mobile,ip);
        }
        return ResultMessageInfo.ofSuccess();
    }

    /**
     * 登录和注册一起.
     *
     * @param mobile
     * @param mobileCode
     * @param request
     * @return
     */
    @GetMapping(value="submit")
    @ResponseBody
    public ResultMessageInfo submit(@RequestParam(value = "mobile") String mobile,
                                    @RequestParam(value = "mobileCode") String mobileCode,
                                 HttpServletRequest request){
        if(StringUtils.isBlank(mobile)){
            return ResultMessageInfo.ofMessage("手机号非法");
        }
        if(StringUtils.isBlank(mobileCode)){
            return ResultMessageInfo.ofMessage("手机验证码非法");
        }

        if (!registerService.isRightMobileCode(mobile, mobileCode)){
            return ResultMessageInfo.ofMessage("手机验证码错误");
        }

        //登录注册处理
        DeviceInfo deviceInfo=getDeviceInfo();
        APPToken token=iUserService.login(mobile,deviceInfo);
        return ResultMessageInfo.ofSuccess(token);

    }

}
